using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using Main.Details;
using ZSW.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using Main;

public class ItemEditor : EditorWindow
{
    private ItemDataList_SO dataBase;
    private List<ItemDetails> itemList;
    private VisualTreeAsset itemRowUXMLTemplate;
    // 左侧列表
    private ListView itemListView;
    // 右侧详情
    private ScrollView ItemDetailsView;
    private VisualElement iconPreview;

    private ItemDetails activeItem;

    [MenuItem("UI Toolkit/ItemEditor")]
    public static void ShowExample()
    {
        ItemEditor wnd = GetWindow<ItemEditor>();
        wnd.titleContent = new GUIContent("ItemEditor");
    }

    public void CreateGUI()
    {
        // Each editor window contains a root VisualElement object
        VisualElement root = rootVisualElement;

        // Import UXML
        var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/UI Builder/ItemEditor.uxml");
        VisualElement labelFromUXML = visualTree.Instantiate();
        root.Add(labelFromUXML);

        itemRowUXMLTemplate = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/UI Builder/ItemRowUXMLTemplate.uxml");

        itemListView = root.Q<VisualElement>("ItemList").Q<ListView>("ListView");

        ItemDetailsView = root.Q<ScrollView>("ItemDetails");

        iconPreview = ItemDetailsView.Q<VisualElement>("Icon");

        root.Q<Button>("AddButton").clicked += OnAddButtonClick;

        root.Q<Button>("DeleteButton").clicked += OnDeleteButtonClick;

        LoadDataBase();

        GenerateListView();
    }

    private void OnDeleteButtonClick()
    {
        if (activeItem != null)
        {
            itemList.Remove(activeItem);
            itemListView.Rebuild();
            ItemDetailsView.visible = false;
        }
    }


    private void OnAddButtonClick()
    {
        ItemDetails newItem = new ItemDetails()
        {
            ItemName = "New Item",
            ItemID = 1000 + itemList.Count,
            ItemPrice = 100,
            SellPercentage = 0.7f
        };

        itemList.Add(newItem);

        itemListView.Rebuild();

        itemListView.SetSelection(itemList.Count - 1);
    }


    private void LoadDataBase()
    {
        dataBase = AssetDatabase.LoadAssetAtPath<ItemDataList_SO>("Assets/Resources/ScriptableObject/ItemDataList_SO.asset");
        if (dataBase == null)
        {
            ZSWFUtil_Debug.LogError(this.GetType().ToString(), "ItemDataList_SO is null 请检查是否创建了ItemDataList_SO文件");
        }
        else
        {
            ZSWFUtil_Debug.Log(this.GetType().ToString(), $"加载物品数据成功 共有{dataBase.ItemDetailsList.Count} 个物品");

            itemList = dataBase.ItemDetailsList;

            EditorUtility.SetDirty(dataBase);
        }
    }

    private void GenerateListView()
    {
        Func<VisualElement> makeItem = () => itemRowUXMLTemplate.CloneTree();

        Action<VisualElement, int> bindItem = (e, i) =>
        {
            if (i < itemList.Count)
            {
                if (itemList[i].ItemIcon == null)
                {
                    e.Q<VisualElement>("Icon").style.backgroundImage = null;
                }
                else
                {
                    e.Q<VisualElement>("Icon").style.backgroundImage = itemList[i].ItemIcon.texture;
                }

                e.Q<Label>("Name").text = itemList[i].ItemName == "" ? "未命名物品" : itemList[i].ItemName;
            }
        };
        itemListView.fixedItemHeight = 60f;
        itemListView.itemsSource = itemList;
        itemListView.makeItem = makeItem;
        itemListView.bindItem = bindItem;

        itemListView.onSelectionChange += OnListSelectionChange;

        ItemDetailsView.visible = false;
    }

    private void OnListSelectionChange(IEnumerable<object> enumerable)
    {
        activeItem = (ItemDetails)enumerable.First();
        GetItemDetails();
        ItemDetailsView.visible = true;
    }

    private void GetItemDetails()
    {
        ItemDetailsView.MarkDirtyRepaint();

        ItemDetailsView.Q<IntegerField>("ItemID").value = activeItem.ItemID;
        ItemDetailsView.Q<IntegerField>("ItemID").RegisterValueChangedCallback(evt =>
        {
            activeItem.ItemID = evt.newValue;
        });

        ItemDetailsView.Q<TextField>("ItemName").value = activeItem.ItemName;
        ItemDetailsView.Q<TextField>("ItemName").RegisterValueChangedCallback(evt =>
        {
            activeItem.ItemName = evt.newValue;
            itemListView.Rebuild();
        });

        ItemDetailsView.Q<EnumField>("ItemType").Init(activeItem.ItemType);
        ItemDetailsView.Q<EnumField>("ItemType").RegisterValueChangedCallback(evt =>
        {
            activeItem.ItemType = (ItemType)evt.newValue;
        });

        iconPreview.style.backgroundImage = activeItem.ItemIcon == null ? null : activeItem.ItemIcon.texture;
        ItemDetailsView.Q<ObjectField>("ItemIcon").value = activeItem.ItemIcon;
        ItemDetailsView.Q<ObjectField>("ItemIcon").RegisterValueChangedCallback(evt =>
        {
            Sprite newIcon = evt.newValue as Sprite;
            activeItem.ItemIcon = newIcon;
            iconPreview.style.backgroundImage = newIcon == null ? null : newIcon.texture;
            itemListView.Rebuild();
        });

        ItemDetailsView.Q<ObjectField>("ItemOnWorldSprite").value = activeItem.ItemOnWorldSprite;
        ItemDetailsView.Q<ObjectField>("ItemOnWorldSprite").RegisterValueChangedCallback(evt =>
        {
            activeItem.ItemOnWorldSprite = evt.newValue as Sprite;
        });

        ItemDetailsView.Q<TextField>("ItemDescription").value = activeItem.ItemDescription;
        ItemDetailsView.Q<TextField>("ItemDescription").RegisterValueChangedCallback(evt =>
        {
            activeItem.ItemDescription = evt.newValue;
        });

        ItemDetailsView.Q<IntegerField>("ItemUseRadius").value = activeItem.ItemUseRadius;
        ItemDetailsView.Q<IntegerField>("ItemUseRadius").RegisterValueChangedCallback(evt =>
        {
            activeItem.ItemUseRadius = evt.newValue;
        });

        ItemDetailsView.Q<Toggle>("CanPickUp").value = activeItem.CanPickUp;
        ItemDetailsView.Q<Toggle>("CanPickUp").RegisterValueChangedCallback(evt =>
        {
            activeItem.CanPickUp = evt.newValue;
        });

        ItemDetailsView.Q<Toggle>("CanDroped").value = activeItem.CanDropped;
        ItemDetailsView.Q<Toggle>("CanDroped").RegisterValueChangedCallback(evt =>
        {
            activeItem.CanDropped = evt.newValue;
        });

        ItemDetailsView.Q<Toggle>("CanCarried").value = activeItem.CanCarried;
        ItemDetailsView.Q<Toggle>("CanCarried").RegisterValueChangedCallback(evt =>
        {
            activeItem.CanCarried = evt.newValue;
        });

        ItemDetailsView.Q<IntegerField>("ItemPrice").value = activeItem.ItemPrice;
        ItemDetailsView.Q<IntegerField>("ItemPrice").RegisterValueChangedCallback(evt =>
        {
            activeItem.ItemPrice = evt.newValue;
        });

        ItemDetailsView.Q<Slider>("SellPrecentage").value = activeItem.SellPercentage;
        ItemDetailsView.Q<Slider>("SellPrecentage").RegisterValueChangedCallback(evt =>
        {
            activeItem.SellPercentage = evt.newValue;
        });

    }
}